// 格式化时间戳
export function formatUnixTime(val, type, isNewdate) {
    // 第一个参数要是字符串类型的
    // type的值对应会返回不同字符串格式的时间值，99=直接返回GMT
    // 不是合法时间会返回false；isNewDate()能判断是否是GMT时间，并最终判断目标值是否能转换成GMT时间
    // # 调用：that.formatTime(time, 2)
    var toDay, newDate
    if (!val) {
        console.log('不合法时间 time val is Empty!');
        return false
    }
    if (isNewDate(val)) { // 判断是否是GMT / new Date()
        newDate = val
    } else if (/^\d+$/.test(val)) { // unix time
        newDate = new Date(Number(val))
    } else if (typeof val === 'string' && val.indexOf('T') > -1) { // UTC
        newDate = formatUTC(val)
    } else if (typeof val === 'string' && val.indexOf('-') > -1) { // nomorl time 2020-10-16 14:31:00
        newDate = new Date(val.replace(/\-/g, '/'))
    } else {
        newDate = val
    }
    if (!isNewDate(newDate)) {
        console.log('newDate is Invalid Date......', newDate);
        return false
    }
    if (type === 97) return Number(new Date()) // 1612767936591 精确到毫秒
    if (type === 98) return Date.parse(newDate) // 1612767936000 精确到秒
    if (type === 99) return newDate
    let Y = newDate.getFullYear()
    let M = ((newDate.getMonth() + 1) >= 10 ? (newDate.getMonth() + 1) : '0' + (newDate.getMonth() + 1))
    let D = (newDate.getDate() >= 10 ? newDate.getDate() : '0' + newDate.getDate())
    let h = newDate.getHours() >= 10 ? newDate.getHours() : '0' + newDate.getHours()
    let m = newDate.getMinutes() >= 10 ? newDate.getMinutes() : '0' + newDate.getMinutes()
    let s = newDate.getSeconds() >= 10 ? newDate.getSeconds() : '0' + newDate.getSeconds()
    if (!type) {
        toDay = Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s // 2018-10-26 10:06:21
    } else if (type === 1) {
        toDay = Y + '-' + M + '-' + D + ' ' + h + ':' + m // 2018-10-26 10:06
    } else if (type === 2) {
        toDay = Y + '-' + M + '-' + D // 2018-10-26
    } else if (type === 3) {
        toDay = M + '-' + D // 10-26
    } else if (type === 4) {
        toDay = [M, D, h, m] // [10,26,00,00]
    } else if (type === 5) {
        toDay = Y + '-' + M // 2020-01
    } else if (type === 6) {
        toDay = h + ':' + m + ':' + s // 13:10:10
    } else if (type === 7) {
        toDay = M + '月' + D + '日' // 10-26
    }
    return toDay
}
// 判断是否是有效的GMT / new Date()时间格式，比如Mon Feb 08 2021 15:05:36 GMT+0800 (China Standard Time)
export function isNewDate(date) {
    return date instanceof Date && !isNaN(date.getTime())
}
// 格式化UTC / 现在时间
export function formatUTC(t, hasZone) {
    // # 该方法服务目的服务于后端输出的'2021-08-18T08:00:00.000+0800'，实际时间为2021-08-18 08:00:00，不考虑时区
    // # hasZone是否修复时区，true 修复 false 不修复
    // # 考虑时区的话：
    // formatUTC('2021-08-18T08:00:00.000+0800');
    // 0时区 = 2021-08-18 08:00:00
    // 8时区 = 2021-08-18 16:00:00
    if (t.indexOf('T') != -1) {
        var y, h; //年份,时间
        var regH = /(T| )(\d\d:\d\d:\d\d)(\.\d+)?/;// 校验时间格式
        h = t.match(regH);
        h = h && h[2]; //拿到时分秒
        y = t.slice(0, t.indexOf('T') + 1); //截取年月日
        if (y.indexOf('-') != -1) y = y.replace(/\-/g, '/')
        if (hasZone) {
            var timestamp = new Date(Date.parse(y.slice(0, -1) + ' ' + h)).getTime() / 1000;
            var off = new Date().getTimezoneOffset() / 60; //当前时差
            timestamp -= off * 60 * 60;
            return new Date(parseInt(timestamp) * 1000)
        } else {
            return new Date(Date.parse(y.slice(0, -1) + ' ' + h))
        }
    }
    return false;
}


// 把字符串转换成unixtime(时间戳)，返回精确度为秒，非毫秒，并兼容IOS
export function dateParse(str) {
    var rst = Date.parse(str.replace(/-/g, '/')) || Date.parse(str)
    rst = rst / 1000
    return rst
}


//防抖
export function _debounce(fn, wait = 300, isImmediate = false) {
    var timerId = null;
    var flag = true;
    return function () {
        var context = this
        var args = arguments
        clearTimeout(timerId)
        if (isImmediate) {
            if (flag) {
                fn.apply(context, args)
                flag = false
            }
            timerId = setTimeout(function () {
                flag = true
            }, wait)
        } else {
            timerId = setTimeout(function () {
                fn.apply(context, args)
            }, wait)
        }
    }
}



// 节流
export function _throttle(fn, wait = 300, isImmediate = false, callback) {
    var flag = true;
    return function () {
        if (flag == true) {
            var context = this
            var args = arguments
            flag = false
            isImmediate && fn.apply(context, args)
            setTimeout(() => {
                !isImmediate && fn.apply(context, args)
                flag = true
                if (callback) callback.apply(context, args);
            }, wait)
        }
    }
}



// 倒计时
export function countDownRefresh(fn, interval, that, timerName, intervalShow) {
    timerName = timerName || 'timer'
    interval = interval || 5
    // 先清空旧计时器
    if (that[timerName]) clearInterval(that[timerName])
    that[intervalShow] = interval
    // 新建计时器
    that[timerName] = setInterval(function () {
        interval--
        if (intervalShow) that[intervalShow] = interval
        // 倒计时结束
        if (interval <= 0) {
            fn()
            if (that[timerName]) clearInterval(that[timerName])
        }
        console.debug('interval... ...', interval)
    }, 1000)
}


// 数组去空
export function arrTrimHandle(arr) {
    var rst = arr.filter(function (val) {
        return val && val.trim()
    })
    return rst
}


// 一个数组是否包含另个数组 type有值对比是否全等于
export function beIncludedArr(smallArr, bigArr, type) {
    var intersection,
        objArr,
        rst
    intersection = smallArr.filter(function (val) {
        val = val && val.trim()
        return bigArr.indexOf(val) > -1
    })
    objArr = type ? bigArr : smallArr
    if (type) console.log('intersection', intersection, objArr);
    if (intersection.length === objArr.length) {
        rst = true
    } else {
        rst = false
    }
    return rst
}



// 一个数组是否包含另个数组
export function equalityArr(arr1, arr2) {
    var rst
    if (arr1.sort().toString() === arr2.sort().toString()) {
        rst = true
    } else {
        rst = false
    }
    return rst
}


// 连续点击运行
export function quickClickRun(fn, that) {
    that.maxClick = 6
    that.limitTime = 3 * 1000
    var now = Date.parse(new Date())
    if (!that.click) {
        that.calculationTime = now
        that.click = 1
    } else {
        that.click++
        if ((that.click > that.maxClick) && (now - that.calculationTime < that.limitTime)) {
            if (fn && typeof fn === 'function') fn()
            that.click = null
            that.calculationTime = null
        } else if (now - that.calculationTime > that.limitTime) {
            that.click = null
            that.calculationTime = null
        }
    }
}


// 从身份证里获取年龄值
export function IdCardAge(userCard) {
    var myDate = new Date();
    var month = myDate.getMonth() + 1;
    var day = myDate.getDate();
    var age = myDate.getFullYear() - userCard.substring(6, 10) - 1;
    if (userCard.substring(10, 12) < month || userCard.substring(10, 12) == month && userCard.substring(12, 14) <= day) {
        age++;
    }
    return age
}


// 去空
export function trimStr(str) {
    str = str.replace(/\s*/g, "");
    return str
}


// 金额数字超千位加逗号
export function thousandAddComma(num) {
    var rt = (num.toString().indexOf('.') !== -1) ? num.toLocaleString() : num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
    return rt
}


// 身份证设置(10，4) 手机号设置（5,2）
// start 从第几位开始添加***
// end 结尾第几位显示
export function desensitizationStr(str, start, end) {
    if (!str) return '';
    var start = start === 0 || start ? start : 1 // 显示前面几位
    var hide = hide ? hide : 1 // 显示后面几位
    var len = str.length
    var symbol = '*'
    var substitute = ''
    var hide = len - start - end
    var rst
    if (hide > 0) {
        for (var i = 0; i < hide; i++) {
            substitute += symbol
        }
        rst = str.substr(0, start) + substitute + str.substr(len - end)
    } else {
        rst = str
    }
    return rst
}

// 姓名脱敏
export function NameDesensitization(name) {
    if (name.length == 3) {
        let arr = name.split('')
        arr[1] = "*"
        return arr.join('')
    } else if (name.length == 2) {
        let arr = name.split('')
        arr[0] = "*"
        // console.log(arr.join(''))
        return arr.join('')

    } else if (name.length == 4) {
        let arr = name.split('')
        arr[1] = "*"
        arr[2] = "*"
        // console.log(arr.join(''))
        return arr.join('')

    } else if (name.length > 4) {
        let arr = name.split('')
        let mid = ""
        for (let i = 0; i < name.length - 2; i++) {
            mid += "*"
        }
        let str = arr[0] + mid + arr[name.length - 1]
        // console.log(str);
        return str
    }
}

// 姓名脱敏 显示姓
export function NameDesensitization1(name) {
    if (!name) return;
    let arr = name.split('')
    let mid = ""
    for (let i = 0; i < name.length - 1; i++) {
        mid += "*"
    }
    let str = arr[0] + mid
    // console.log(str);
    return str
}

export function RegularVerification(str, type) {
    /**
     * type = 1 : 是否是中文
     * type = 2 : 是否是手机号
     * type = 3 : 是否是身份证
     * type = 4 : 是否是4位验证码
     * type = 5 : 是否是6位验证码
     * type = 6 : 普通密码 (以字母开头，长度在6~18之间，只能包含字母、数字和下划线)
     * type = 7 : 强密码(必须包含大小写字母和数字的组合，不能使用特殊字符，长度在 8-10 之间)
     * type = 8 : 强密码(必须包含大小写字母和数字的组合，可以使用特殊字符，长度在 8-10 之间)
     * type = 9 : Email地址
     * type = 10 : 姓名中间有空格不能提交，英文名有空格可以提交
     * 
     */
    let name = /^[\u4e00-\u9fa5]{0,}$/
    let phone = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|16[0|1|2|3|4|5|6|7|8|9]|17[0|1|2|3|4|5|6|7|8|9]|19[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
    let id = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
    let CommonPassword = /^[a-zA-Z]\w{5,17}$/
    let StrongPassword1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{8,10}$/
    let StrongPassword2 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$/
    let Email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
    let Code4 = /^\d{4}$/
    let Code6 = /^\d{6}$/
    let NamePhone = /^(?:[\u4e00-\u9fa5]+)(?:·[\u4e00-\u9fa5]+)*$|^[a-zA-Z0-9]+\s*[\.·\-()a-zA-Z]*[a-zA-Z]+$/

    if (type == 1) {
        return name.test(str)
    } else if (type == 2) {
        return phone.test(str)
    } else if (type == 3) {
        return id.test(str)
    } else if (type == 4) {
        return Code4.test(str)
    } else if (type == 5) {
        return Code6.test(str)
    } else if (type == 6) {
        return CommonPassword.test(str)
    } else if (type == 7) {
        return StrongPassword1.test(str)
    } else if (type == 8) {
        return StrongPassword2.test(str)
    } else if (type == 9) {
        return Email.test(str)
    }else if(type == 10){
        return NamePhone.test(str)
    }

}

// 通过身份证识别性别
export function getSex(v) {
    if (v != "") {
        let sexStr = "";
        if (parseInt(v.slice(-2, -1)) % 2 == 1) {
            sexStr = "男";
        } else {
            sexStr = "女";
        }
        return sexStr;
    }
}

// 将字符串的字符全部转换为小写字符
export function lowerCase(str) {
    let arr = str.split("");
    let newStr = "";
    //通过for循环遍历数组
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] >= 'A' && arr[i] <= 'Z')
            newStr += arr[i].toLowerCase();
        else
            newStr += arr[i];
    }
    return newStr;
}

// 将字符串的字符全部转换为大写字符
export function upperCase(str) {
    let arr = str.split("");
    let newStr = "";
    // 通过数组的forEach方法来遍历数组
    arr.forEach(function (value) {
        if (value >= 'a' && value <= 'z')
            newStr += value.toUpperCase();
        else
            newStr += value;
    });
    return newStr;
}

//阿拉伯数字转换成大写汉字
export default function numberParseChina(money){
  //汉字的数字
    var cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
    //基本单位
    var cnIntRadice = new Array('', '拾', '佰', '仟');
    //对应整数部分扩展单位
    var cnIntUnits = new Array('', '万', '亿', '兆');
    //对应小数部分单位
    var cnDecUnits = new Array('角', '分', '毫', '厘');
    //整数金额时后面跟的字符
    var cnInteger = '整';
    //整型完以后的单位
    var cnIntLast = '圆';
    //最大处理的数字
    var maxNum = 999999999999999.9999;
    //金额整数部分
    var integerNum;
    //金额小数部分
    var decimalNum;
    //输出的中文金额字符串
    var chineseStr = '';
    //分离金额后用的数组，预定义
    var parts;
    if (money == '') { return ''; }
    money = parseFloat(money);
    if (money >= maxNum) {
      //超出最大处理数字
      return '';
    }
    if (money == 0) {
      chineseStr = cnNums[0] + cnIntLast + cnInteger;
      return chineseStr;
    }
    //转换为字符串
    money = money.toString();
    if (money.indexOf('.') == -1) {
      integerNum = money;
      decimalNum = '';
    } else {
      parts = money.split('.');
      integerNum = parts[0];
      decimalNum = parts[1].substr(0, 4);
    }
    //获取整型部分转换
    if (parseInt(integerNum, 10) > 0) {
      var zeroCount = 0;
      var IntLen = integerNum.length;
      for (var i = 0; i < IntLen; i++) {
        var n = integerNum.substr(i, 1);
        var p = IntLen - i - 1;
        var q = p / 4;
        var m = p % 4;
        if (n == '0') {
          zeroCount++;
        } else {
          if (zeroCount > 0) {
            chineseStr += cnNums[0];
          }
          //归零
          zeroCount = 0;
          chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
        }
        if (m == 0 && zeroCount < 4) {
          chineseStr += cnIntUnits[q];
        }
      }
      chineseStr += cnIntLast;
    }
    //小数部分
    if (decimalNum != '') {
      var decLen = decimalNum.length;
      for (var i = 0; i < decLen; i++) {
        var n = decimalNum.substr(i, 1);
        if (n != '0') {
          chineseStr += cnNums[Number(n)] + cnDecUnits[i];
        }
      }
    }
    if (chineseStr == '') {
      chineseStr += cnNums[0] + cnIntLast + cnInteger;
    } else if (decimalNum == '') {
      chineseStr += cnInteger;
    }
    return chineseStr;
}